<?php

namespace Ignus\View\Node;

use Ignus\View\Node;
use Ignus\View\Compiler;
use Ignus\View\NodeInterface;
use Ignus\View\NodeOutputInterface;
use Ignus\View\Node\Expression\Constant;

class IncludeNode extends Node implements NodeOutputInterface
{
    public function __construct(Expression $expr, Expression $variables = null, $only = false, $ignoreMissing = false, $lineno, $tag = null)
    {
        parent::__construct(array('expr' => $expr, 'variables' => $variables), array('only' => (boolean) $only, 'ignore_missing' => (boolean) $ignoreMissing), $lineno, $tag);
    }

    public function compile(Compiler $compiler)
    {
        $compiler->addDebugInfo($this);

        if ($this->getAttribute('ignore_missing')) {
            $compiler
                ->write("try {\n")
                ->indent();
        }

        if ($this->getNode('expr') instanceof Constant) {
            $compiler
                ->write("\$this->env->loadTemplate(")
                ->subcompile($this->getNode('expr'))
                ->raw(")->display(");
        }
        else {
            $compiler
                ->write("\$template = \$this->env->resolveTemplate(")
                ->subcompile($this->getNode('expr'))
                ->raw(");\n")
                ->write('$template->display(');
        }

        if (false === $this->getAttribute('only')) {
            if (null === $this->getNode('variables')) {
                $compiler->raw('$context');
            }
            else {
                $compiler
                    ->raw('array_merge($context, ')
                    ->subcompile($this->getNode('variables'))
                    ->raw(')');
            }
        }
        else {
            if (null === $this->getNode('variables')) {
                $compiler->raw('array()');
            }
            else {
                $compiler->subcompile($this->getNode('variables'));
            }
        }

        $compiler->raw(");\n");

        if ($this->getAttribute('ignore_missing')) {
            $compiler
                ->outdent()
                ->write("} catch (Twig_Error_Loader \$e) {\n")
                ->indent()
                ->write("// ignore missing template\n")
                ->outdent()
                ->write("}\n\n");
        }
    }
}
